package edu.whut.mall.user.controller;

import edu.whut.mall.common.api.ResponseMap;
import edu.whut.mall.user.service.IMailService;
import edu.whut.mall.user.service.ISecurityCodeService;
import edu.whut.mall.user.service.IUserService;
import edu.whut.mall.user.vo.UserVo;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author smq
 * @Date 2021/8/19 9:28
 * @Uint d9lab
 * @Description:
 */
@RequiredArgsConstructor
@RequestMapping("/email")
@RestController
@Api(value = "邮箱验证码模块", tags = {"邮箱验证码模块"})
public class EmailController {

    private final ISecurityCodeService securityCodeService;
    private final IMailService mailService;
    private final IUserService userService;


    private static final String EMAIL_TITLE = "您正在使用D9Lab实验室官方邮件服务";
    private static final String TITLE = "D9Lab实验室";

    @GetMapping("/send_code")
    public Map<String, Object> sendCode(String email) {
        ResponseMap map = ResponseMap.getInstance();
        Assert.hasLength(email, "请输入邮箱地址");
        UserVo exist = userService.getByEmail(email);
        Assert.isNull(exist, "该邮箱已被使用");
        String code = securityCodeService.generateCode(email);
        Map<String, Object> context = new HashMap<>();
        context.put("code", code);
        String title = MessageFormat.format(EMAIL_TITLE, TITLE);
        mailService.sendTemplateEmail(email, title, "email_code.ftl", context);
        return map.putSuccess("邮件发送成功");
    }
}
